/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.system.rest;

import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.base.AjaxResult;
import me.zhengjie.config.RsaProperties;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.vo.UserPassVo2;
import me.zhengjie.modules.system.service.DataService;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.vo.UserPassVo;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.*;
import me.zhengjie.modules.system.service.VerifyService;
import me.zhengjie.service.*;
import me.zhengjie.service.dto.AppAreaDto;
import me.zhengjie.service.dto.AppEventDto;
import me.zhengjie.service.dto.AppMessageQueryCriteria;
import me.zhengjie.service.dto.AppWorkDto;
import me.zhengjie.utils.*;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.enums.CodeEnum;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Zheng Jie
 * @date 2018-11-23
 */
@Api(tags = "系统：用户管理")
@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final PasswordEncoder passwordEncoder;
    private final UserService userService;
    private final AppAreaService areaService;
    private final DataService dataService;
    private final DeptService deptService;
    private final RoleService roleService;
    private final VerifyService verificationCodeService;
    private final AppWorkService appWorkService;
    private final AppEventService appEventService;
    private final AppMessageService appMessageService;
    private final AppMessageToService appMessageToService;

    @ApiOperation("首页数据")
    @GetMapping(value = "/first")
    public AjaxResult first(){

        UserDto user = userService.findById(SecurityUtils.getCurrentUserId());
        Map ret = new HashMap();
        ret.put("zhaohu1","欢迎进入智慧林长管理系统>>>");
        ret.put("zhaohu2",DateUtils.getHello());
        ret.put("nickName",user.getNickName());
        String roleName = userService.findRoleNameByUser(user.getLzzw());
        ret.put("roleName",roleName);

        Integer userId = SecurityUtils.getCurrentUserId().intValue();

        //查询未读消息数量
        Integer msgNum = appMessageToService.msgCount(userId);
        ret.put("msgNum",msgNum);

        //查询正在进行中的任务
        Integer workId = appWorkService.selectWorking(userId);
        ret.put("workId",workId);

        //查询巡护任务数量（未完成，未过期）
        Integer workNum = appWorkService.selUndoWorkCount(userId);
        ret.put("workNum",workNum>9?""+workNum:"0"+workNum);

        //查询收到的事件数量（未处理）
        Integer eventNum = appEventService.selUndoEventCount(userId);
        ret.put("eventNum",eventNum>9?""+eventNum:"0"+eventNum);

        //查询紧急事件（滚动显示）
        List<MsgDto> msg = new LinkedList<>();
        List<AppEventDto> list = appEventService.queryAllIndex(userId);
        if(list.size()>0){
            for(AppEventDto item : list){
                msg.add(new MsgDto(1,item.getEventId(),item.getTitle()));
            }
        }

        //查询紧急巡护任务（滚动显示）
        List<AppWorkDto> list2 = appWorkService.queryAllIndex(userId);
        if(list2.size()>0){
            for(AppWorkDto item : list2){
                msg.add(new MsgDto(2,item.getWorkId(),item.getTitle()));
            }
        }
        if(msg.size()>0) {
            ret.put("list",msg);
        }else{
            ret.put("list",new String[0]);
        }

        return AjaxResult.success(ret);
    }

    @ApiOperation("我的")
    @GetMapping(value = "/info")
    public AjaxResult info(){

        UserDto user = userService.findById(SecurityUtils.getCurrentUserId());
        Integer userId = SecurityUtils.getCurrentUserId().intValue();
        Map ret = new HashMap();
        ret.put("nickName",user.getNickName());
        String roleName = userService.findRoleNameByUser(user.getLzzw());
        ret.put("roleName",roleName);
        ret.put("workNo",user.getWorkNo());
        ret.put("avatarPath",user.getAvatarPath());
        ret.put("fanwei","宜都市陆城区");

        ret.put("dk",0);

        //查询已巡护任务次数
        Integer workNum = appWorkService.selWorkCount(userId);
        ret.put("workNum",workNum>9?workNum:"0"+workNum);

        //查询已上报事件数量
        Integer eventNum = appEventService.selEventCount(userId);
        ret.put("eventNum",eventNum>9?eventNum:"0"+eventNum);

        //总里程
        float totalMile = appWorkService.selWorkMilesSum(userId);
        //保留1位小数
        totalMile = (float)(Math.round(totalMile*10))/10;
        ret.put("totalMile",totalMile);

        return AjaxResult.success(ret);
    }

    /**
     * 选择人员
     * @param type 1上报选择处理人，2回复分配处理人
     * @param keyword
     * @return
     */
    @ApiOperation("选择人员")
    @GetMapping(value = "/seluser")
    public AjaxResult seluser(@RequestParam(defaultValue = "1") int type,
                              @RequestParam(defaultValue = "") String keyword){

        UserDto user = userService.findById(SecurityUtils.getCurrentUserId());
        //查询当前会员角色情况 1林长，2兼职护林员，3专职护林员
        int role = userService.findRoleByUser(user);
        //查询上级责任区
        AppAreaDto areaDto = areaService.findById(user.getAreaId());
        Integer areaIdFid = areaDto.getFid();

//        UserQueryCriteria criteria = new UserQueryCriteria();
//        criteria.setEnabled(true);
//        if(!keyword.equals("")){
//            criteria.setBlurry(keyword);
//        }
//        criteria.setType(2);
//        criteria.setIdNotMe(SecurityUtils.getCurrentUserId());
//        List<UserDto> userLists = userService.queryAll(criteria);

        List<User> userLists = userService.selUsersByRole(type,areaIdFid.intValue(),user.getAreaId(),role);
        List<UserSelDto> rets = new LinkedList<>();
        for (User item : userLists){
            //跳过自己
            if(item.getId().equals(SecurityUtils.getCurrentUserId())){
                continue;
            }
            UserSelDto ret = new UserSelDto();
            ret.setUserId(item.getId());
            ret.setNickName(item.getNickName());
            ret.setPhone(item.getPhone());
            String roleName = userService.findRoleNameByUser(item.getLzzw());
            ret.setRoleName(roleName);
            ret.setAvatarPath(item.getAvatarPath());
            rets.add(ret);
        }
        return AjaxResult.success(rets);
    }


    @ApiOperation("通讯录")
    @GetMapping(value = "/contact")
    public AjaxResult contact(@RequestParam(defaultValue = "") String keyword, Pageable pageable){

        UserQueryCriteria criteria = new UserQueryCriteria();
        criteria.setEnabled(true);
        if(!keyword.equals("")){
            criteria.setBlurry(keyword);
        }
        //表示非管理员
        criteria.setType(2);
//        criteria.setIdNotMe(SecurityUtils.getCurrentUserId());

        return AjaxResult.success(userService.queryAll2(criteria,pageable));
    }


    @ApiOperation("消息列表")
    @GetMapping(value = "/message")
    public AjaxResult message(AppMessageQueryCriteria criteria,
                              @PageableDefault(sort = {"msgId"}, direction = Sort.Direction.DESC) Pageable pageable){
        return AjaxResult.success(appMessageService.queryAllApi(criteria,pageable));
    }

    @ApiOperation("消息已读")
    @GetMapping(value = "/messageRead")
    public AjaxResult messageRead(@RequestParam(defaultValue = "") Integer msgId){
        appMessageToService.read(msgId);
        return AjaxResult.success();
    }



    @ApiOperation("导出用户数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('user:list')")
    public void exportUser(HttpServletResponse response, UserQueryCriteria criteria) throws IOException {
        userService.download(userService.queryAll(criteria), response);
    }

    @ApiOperation("查询用户和人员管理")
    @GetMapping
    @PreAuthorize("@el.check('user:list')")
    public ResponseEntity<Object> queryUser(@RequestParam(defaultValue = "1") Integer type,
                                            UserQueryCriteria criteria, Pageable pageable){

        if(SecurityUtils.getCurrentUserId().intValue() != 1) {
            criteria.setIdNotMe(1L);
        }
        if(type == 1){
            //系统用户
            criteria.setBind(1);
        }else{
            //人员管理
            criteria.setType(type);
        }
        if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
            criteria.getDeptIds().add(criteria.getDeptId());
            // 先查找是否存在子节点
            List<Dept> data = deptService.findByPid(criteria.getDeptId());
            // 然后把子节点的ID都加入到集合中
            criteria.getDeptIds().addAll(deptService.getDeptChildren(data));
        }
        // 数据权限
        List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));
        // criteria.getDeptIds() 不为空并且数据权限不为空则取交集
        if (!CollectionUtils.isEmpty(criteria.getDeptIds()) && !CollectionUtils.isEmpty(dataScopes)){
            // 取交集
            criteria.getDeptIds().retainAll(dataScopes);
            if(!CollectionUtil.isEmpty(criteria.getDeptIds())){
                return new ResponseEntity<>(userService.queryAll(criteria,pageable),HttpStatus.OK);
            }
        } else {
            // 否则取并集
            criteria.getDeptIds().addAll(dataScopes);
            Object t = userService.queryAll(criteria,pageable);
            return new ResponseEntity<>(t,HttpStatus.OK);
        }
        return new ResponseEntity<>(PageUtil.toPage(null,0),HttpStatus.OK);
    }



    @ApiOperation("查询单个用户")
    @GetMapping(value = "/one")
    public ResponseEntity<Object> queryUserOne( @RequestParam(defaultValue = "") String phone){
        return new ResponseEntity<>(userService.findByName(phone),HttpStatus.OK);
    }

    @ApiOperation("新增人员")
    @PostMapping(value = "/add")
    @PreAuthorize("@el.check('user:add')")
    public ResponseEntity<Object> createUserApi(@Validated @RequestBody User resources){
        checkLevel(resources);
        if(StringUtils.isEmpty(resources.getPassword())){
            // 默认密码 123456
            resources.setPassword(passwordEncoder.encode("123456"));
        }else {
            resources.setPassword(passwordEncoder.encode(resources.getPassword().trim()));
        }
        resources.setEnabled(true);
        resources.setType(2);   //前端员工
        userService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("新增用户")
    @ApiOperation("新增用户")
    @PostMapping
    @PreAuthorize("@el.check('user:add')")
    public ResponseEntity<Object> createUser(@Validated @RequestBody User resources){
        checkLevel(resources);
        // 默认密码 123456
        resources.setPassword(passwordEncoder.encode("123456"));
        resources.setType(1);   //后台管理员
        userService.create(resources);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @Log("修改用户")
    @ApiOperation("修改用户")
    @PutMapping
    @PreAuthorize("@el.check('user:edit')")
    public ResponseEntity<Object> updateUser(@Validated(User.Update.class) @RequestBody User resources) throws Exception {
        checkLevel(resources);
        if(StringUtils.isEmpty(resources.getPassword())){
            // 默认密码 123456
            resources.setPassword(passwordEncoder.encode("123456"));
        }else {
            resources.setPassword(passwordEncoder.encode(resources.getPassword().trim()));
        }
        userService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("修改用户：个人中心")
    @ApiOperation("修改用户：个人中心")
    @PutMapping(value = "center")
    public ResponseEntity<Object> centerUser(@Validated(User.Update.class) @RequestBody User resources){
        if(!resources.getId().equals(SecurityUtils.getCurrentUserId())){
            throw new BadRequestException("不能修改他人资料");
        }
        userService.updateCenter(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除用户")
    @ApiOperation("删除用户")
    @DeleteMapping
    @PreAuthorize("@el.check('user:del')")
    public ResponseEntity<Object> deleteUser(@RequestBody Set<Long> ids){
        for (Long id : ids) {
            Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
            Integer optLevel =  Collections.min(roleService.findByUsersId(id).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
            if (currentLevel > optLevel) {
                throw new BadRequestException("角色权限不足，不能删除：" + userService.findById(id).getUsername());
            }
        }
        userService.delete(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改密码-前台")
    @PostMapping(value = "/updatePass")
    public AjaxResult updateUserPass(@RequestBody UserPassVo passVo) throws Exception {
//        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPassword());
//        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPassword());
        String oldPass = passVo.getOldPassword();
        String newPass = passVo.getNewPassword();
        if(StringUtils.isEmpty(newPass)){
            return AjaxResult.error("参数错误");
        }
        UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!StringUtils.isEmpty(oldPass)){
            if(!passwordEncoder.matches(oldPass, user.getPassword())){
                return AjaxResult.error("修改失败，旧密码错误");
            }
            if(passwordEncoder.matches(newPass, user.getPassword())){
                return AjaxResult.error("新密码不能与旧密码相同");
            }
        }
        userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
        return AjaxResult.success("修改成功");
    }

    @ApiOperation("修改密码-后台")
    @PostMapping(value = "/updatePass2")
    public ResponseEntity<Object> updateUserPass(@RequestBody UserPassVo2 passVo) throws Exception {
        String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
        String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());
        UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(oldPass, user.getPassword())){
            throw new BadRequestException("修改失败，旧密码错误");
        }
        if(passwordEncoder.matches(newPass, user.getPassword())){
            throw new BadRequestException("新密码不能与旧密码相同");
        }
        userService.updatePass(user.getUsername(),passwordEncoder.encode(newPass));
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @ApiOperation("修改头像")
    @PostMapping(value = "/updateAvatar")
    public ResponseEntity<Object> updateUserAvatar(@RequestParam MultipartFile avatar){
        return new ResponseEntity<>(userService.updateAvatar(avatar), HttpStatus.OK);
    }

    @Log("修改邮箱")
    @ApiOperation("修改邮箱")
    @PostMapping(value = "/updateEmail/{code}")
    public ResponseEntity<Object> updateUserEmail(@PathVariable String code,@RequestBody User user) throws Exception {
        String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword());
        UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername());
        if(!passwordEncoder.matches(password, userDto.getPassword())){
            throw new BadRequestException("密码错误");
        }
        verificationCodeService.validated(CodeEnum.EMAIL_RESET_EMAIL_CODE.getKey() + user.getEmail(), code);
        userService.updateEmail(userDto.getUsername(),user.getEmail());
        return new ResponseEntity<>(HttpStatus.OK);
    }

    /**
     * 如果当前用户的角色级别低于创建用户的角色级别，则抛出权限不足的错误
     * @param resources /
     */
    private void checkLevel(User resources) {
        Integer currentLevel =  Collections.min(roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList()));
        Integer optLevel = roleService.findByRoles(resources.getRoles());
        if (currentLevel > optLevel) {
            throw new BadRequestException("角色权限不足");
        }
    }
}
